﻿<%@ WebHandler Language="C#" Class="ZSNotProductMaterialApplyBillHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

public class ZSNotProductMaterialApplyBillHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    NotProductMaterialApplyBillBusiness m_amab = new NotProductMaterialApplyBillBusiness();
    SealAndIssueBusiness m_issueData = new SealAndIssueBusiness();
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    SendRequestBusiness send_b = new SendRequestBusiness();
    #region 页面初始化
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetNPMaterialApplyBill": //申领单---查询
                    GetNPMaterialApplyBill(context);
                    break;
                case "SaveNPMaterialApplyBill"://申领单---新增、保存
                    SaveNPMaterialApplyBill(context);
                    break;
                case "SubmitNPMaterialApplyBill"://申领单---提交
                    SubmitNPMaterialApplyBill(context);
                    break;
                case "ConfirmNPMaterialApplyBill"://申领单---确认
                    ConfirmNPMaterialApplyBill(context);
                    break;
                case "AuditNPMaterialApplyBill"://申领单---审核
                    AuditNPMaterialApplyBill(context);
                    break;
                case "RetrunNPMaterialApplyBill"://申领单---退回
                    RetrunNPMaterialApplyBill(context);
                    break;
                case "DaleteNPMaterialApplyBill"://申领单---删除
                    DaleteNPMaterialApplyBill(context);
                    break;    
                case "GetNPMaterial"://
                    GetNPMaterial(context);
                        break;
                case "GetContainerNo"://
                        GetContainerNo(context);
                        break;
                case "GetUom"://
                        GetUom(context);
                        break;
                case "GetWorkFlowData"://
                        GetWorkFlowData(context);
                        break;
                case "GetWorkcenterByFactory":
                        GetWorkcenterByFactory(context);
                        break;
                case "GetTeamByWorkcenter":
                        GetTeamByWorkcenter(context);
                        break;
                case "GetSumNPMaterialByYear":
                        GetSumNPMaterialByYear(context);
                        break;
                case "GetSumNPMaterialByMonth":
                        GetSumNPMaterialByMonth(context);
                        break;
                case "ReciveConfirmNPMaterialApplyBill": //申领单--收料确认
                        ReciveConfirmNPMaterialApplyBill(context); 
                        break;
                //--------------定额消耗设定----------------
                case "AddYearAndMonth"://添加（年、月）定额消耗
                        AddYearAndMonth(context);
                        break;
                case "UpdateYearAndMonth"://年、月定额消耗设定--更新
                        UpdateYearAndMonth(context);
                        break;
                case "DeleteYearAndMonthConsumeQuota":
                        DeleteYearAndMonthConsumeQuota(context);
                        break;
                case "GetYearConsumeQuota"://材料消耗定稿(按年)
                        GetYearConsumeQuota(context);
                        break;
                case "GetMonthConsumeQuota"://材料消耗定稿(按月)
                        GetMonthConsumeQuota(context);
                        break;
                default :
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    #endregion

    #region 方法
    /// <summary>
    /// 申领单---（分页）查询
    /// </summary>
    /// <param name="context"></param>
    protected void GetNPMaterialApplyBill(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("Description", dt.Rows[0]["Description"].ToString());
        para.Add("materialName", dt.Rows[0]["materialName"].ToString());
        if (dt.Columns.Contains("Status")) {
            para.Add("Status", dt.Rows[0]["Status"].ToString());
        } else {
            para.Add("Status","3");//材料收料确认使用
        }
        para.Add("startedate", dt.Rows[0]["startedate"].ToString());
        para.Add("enddate", dt.Rows[0]["enddate"].ToString());
        para.Add("WorkcenterID", m_UserInfo.WorkCenterID.ToString());
        para.Add("PageSize", pageSize);
        para.Add("CurrentPageIndex", pageNumber);
        uMESProcessResult result = m_amab.GetAuxMaterialApplyBill(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 申领单---新增、保存
    /// </summary>
    /// <param name="context"></param>
    protected void SaveNPMaterialApplyBill(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var ZSNPMATERIALAPPLYBILLID = dt.Rows[0]["ZSNPMATERIALAPPLYBILLID"].ToString();
        var strSequence = "000000" + m_amab.GetAuxMaterialApplyCount();
        var BillNo =  DateTime.Now.ToString("yyyyMMdd") + strSequence.Substring(strSequence.Length - 4);
        var para = new Dictionary<string, string>();
        para.Add("ZSNPMATERIALAPPLYBILLID", string.IsNullOrWhiteSpace(ZSNPMATERIALAPPLYBILLID) ? Guid.NewGuid().ToString() : ZSNPMATERIALAPPLYBILLID);//唯一ID
        para.Add("ZSNPMATERIALAPPLYBILLNO", BillNo);
        para.Add("MATERIALCODE", dt.Rows[0]["MATERIALCODE"].ToString());
        para.Add("APPLYQTY", dt.Rows[0]["APPLYQTY"].ToString());
        para.Add("UOMID", dt.Rows[0]["UOMID"].ToString());
        para.Add("TOGETHERFLAG", dt.Rows[0]["TOGETHERFLAG"].ToString());
        para.Add("WORKFLOWSTEPID", dt.Rows[0]["WORKFLOWSTEPID"].ToString());
        para.Add("PURPOSE", dt.Rows[0]["PURPOSE"].ToString());
        para.Add("APPLYEMPLOYEEID", m_UserInfo.EmployeeID.ToString());
        para.Add("WORKCENTERID", m_UserInfo.WorkCenterID.ToString());
        para.Add("TEAMID", m_UserInfo.TeamID.ToString());
        result.Result = string.IsNullOrWhiteSpace(ZSNPMATERIALAPPLYBILLID) ? m_amab.InsertAuxMaterialApplyBill(para) : m_amab.UpdateAuxMaterialApplyBill(para);
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 申领单---提交
    /// </summary>
    /// <param name="context"></param>
    protected void SubmitNPMaterialApplyBill(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var para=new Dictionary<string,string>();
        para.Add("ZSNPMATERIALAPPLYBILLID", context.Request["ids"].ToString());
        para.Add("Status","1");
        result.Result = m_amab.UpdateAuxMaterialApplyBill(para);
        result.Message = result.Result ? "提交成功" : "提交失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 申领单---确认
    /// </summary>
    /// <param name="context"></param>
    protected void ConfirmNPMaterialApplyBill(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var para = new Dictionary<string, string>();
        para.Add("ZSNPMATERIALAPPLYBILLID", context.Request["ids"].ToString());
        para.Add("CONFIRMEMPLOYEEID", m_UserInfo.EmployeeID.ToString());
        result.Result = m_amab.UpdateAuxMaterialApplyBill(para);
        result.Message = result.Result ? "确认成功" : "确认失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
   /// <summary>
    /// 申领单---审核
   /// </summary>
   /// <param name="context"></param>
    protected void AuditNPMaterialApplyBill(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var para = new Dictionary<string, string>();
        para.Add("ZSNPMATERIALAPPLYBILLID", context.Request["ids"].ToString());
        para.Add("AUDITEMPLOYEEID", m_UserInfo.EmployeeID.ToString());
        result.Result = m_amab.UpdateAuxMaterialApplyBill(para);
        //材料申领任务生成材料临时配送任务
        if (result.Result) { Add(context); }
        result.Message = result.Result ? "审核成功" : "审核失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    protected void Add(HttpContext context)//材料添加临时配送
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        foreach(DataRow  row in dt.Rows){
            if (!string.IsNullOrWhiteSpace(row["WORKFLOWSTEPID"].ToString()) && !string.IsNullOrWhiteSpace(row["TOGETHERFLAG"].ToString()))
            {
                var para = new Dictionary<string, string>();
                para.Add("ZSREQUIREDTOOLSTRANSPORTID", row["ZSNPMATERIALAPPLYBILLID"].ToString());
                para.Add("ENGINEPARTPLANID", GetEnginepanrtPlanIdByContanerNo(row["TOGETHERFLAG"].ToString()));
                para.Add("WORKFLOWSTEPID", row["WORKFLOWSTEPID"].ToString());
                para.Add("CREATEEMPLOYEEID", m_UserInfo.EmployeeID.ToString());
                para.Add("TRANSPORTTYPE", "3");
                para.Add("ZsRTTransportChildID", Guid.NewGuid().ToString());
                para.Add("ToolID", dt.Rows[0]["MATERIALCODE"].ToString());
                para.Add("Qty", dt.Rows[0]["APPLYQTY"].ToString());
                para.Add("APPLYTYPE", "2");
                para.Add("PURPOSE", row["PURPOSE"].ToString());
                para.Add("ProductBatchNo", "");
                para.Add("STATUS", "0");
                send_b.InsertZsRequiredToolsTransport(para); 
            }
        }
    }
    protected string GetEnginepanrtPlanIdByContanerNo(string ContanerNo)
    {
        var id = string.Empty;
        string sqlStr = " SELECT e.ENGINEPARTPLANID,w.SEQUENCE FROM ENGINEPARTPLAN e LEFT JOIN WORKFLOWSTEP w ON w.WORKFLOWSTEPID =e.WORKFLOWSTEPID WHERE e.CONTAINERNO ='" + ContanerNo + "' ORDER BY w.SEQUENCE";
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sqlStr);
        if(dt.Rows.Count>0){
            id = dt.Rows[0]["ENGINEPARTPLANID"].ToString();
        }
        return id;
    }
    /// <summary>
    /// 申领单---退回
    /// </summary>
    /// <param name="context"></param>
    protected void RetrunNPMaterialApplyBill(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var para = new Dictionary<string, string>();
        para.Add("ZSNPMATERIALAPPLYBILLID", context.Request["ids"].ToString());
        if (context.Request["type"].ToString() == "1")
        {
            para.Add("RETURNREASON", context.Request["RETURNREASON"].ToString());
        }
        else {
            para.Add("AUDITRETURNREASON", context.Request["RETURNREASON"].ToString());
        }
        result.Result = m_amab.UpdateAuxMaterialApplyBill(para);
        result.Message = result.Result ? "退回成功" : "退回失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    protected void DaleteNPMaterialApplyBill(HttpContext context) {
        uMESProcessResult result = new uMESProcessResult();
        var para = new Dictionary<string, string>();
        para.Add("ZSNPMATERIALAPPLYBILLID", context.Request["ids"].ToString());
        para.Add("delete","");
        result.Result = m_amab.UpdateAuxMaterialApplyBill(para);
        result.Message = result.Result ? "删除成功" : "删除失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 材料信息
    /// </summary>
    /// <param name="context"></param>
    protected void GetNPMaterial(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var name = context.Request["name"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("Name", name);
        result.DBTable = m_amab.GetAuxMaterial(para);
        result.Result = result.DBTable.Rows.Count > 0;
        result.Message = result.Result ? "" : "查询不到材料信息";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 任务单信息
    /// </summary>
    /// <param name="context"></param>
    protected void GetContainerNo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        var name = context.Request["name"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("Name", name);
        result.DBTable = m_amab.GetContainerNo(para);
        result.Result = result.DBTable.Rows.Count > 0;
        result.Message = result.Result ? "" : "查询不到任务单信息";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 单位
    /// </summary>
    /// <param name="context"></param>
    protected void GetUom(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        result.DBTable = m_amab.GetUom();
        result.Result = result.DBTable.Rows.Count > 0;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 工序查询
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkFlowData(HttpContext context)
    {
        string WorkFlowId = context.Request["workflowid"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        result.DBTable = m_issueData.GetWorkFlowData(WorkFlowId);
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取工区信息
    /// </summary>
    /// <param name="context"></param>
    public void GetWorkcenterByFactory(HttpContext context)
    {
        var wcdt = commonBusiness.GetWorkCenterByFacoryID(m_UserInfo.FactoryID.ToString(), true);
        //var drs = wcdt.Select(" notes is null or notes <>'已注销' ");
        //if (drs.Length > 0)
        //{
        //    wcdt = drs.CopyToDataTable();
        //}
        context.Response.Write(JsonConvert.SerializeObject(wcdt));
    }

    /// <summary>
    /// 获取班组
    /// </summary>
    /// <param name="context"></param>
    public void GetTeamByWorkcenter(HttpContext context)
    {
        if (string.IsNullOrWhiteSpace(context.Request["workcenterId"].ToString()))
        {
            return;
        }
        var dt = commonBusiness.GetTeam(context.Request["workcenterId"].ToString());
        var re = dt.DefaultView.ToTable(true, "TEAMID", "TEAMNAME");
        context.Response.Write(JsonConvert.SerializeObject(re));
    }
    /// <summary>
    /// 材料消耗统计(按年)
    /// </summary>
    /// <param name="context"></param>
    protected void GetSumNPMaterialByYear(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("Description", dt.Rows[0]["Description"].ToString());
        para.Add("NPmaterialName", dt.Rows[0]["NPmaterialName"].ToString());
        para.Add("TeamID", dt.Rows[0]["TeamID"].ToString());
        para.Add("yearmonth", dt.Rows[0]["yearmonth"].ToString());
        para.Add("WorkcenterID", dt.Rows[0]["WorkcenterID"].ToString());
        para.Add("PageSize", pageSize);
        para.Add("CurrentPageIndex", pageNumber);
        uMESProcessResult result = m_amab.GetSumAuxMaterialByYear(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 材料消耗统计(按月)
    /// </summary>
    /// <param name="context"></param>
    protected void GetSumNPMaterialByMonth(HttpContext context)
    {
        var para = new Dictionary<string, string>();
        para.Add("IDS", context.Request["ids"].ToString());
        para.Add("yearmonth", context.Request["yearmonth"].ToString());
        para.Add("WorkcenterID", context.Request["WorkcenterID"].ToString());
        uMESProcessResult result=new uMESProcessResult();
        result.DBTable= m_amab.GetSumAuxMaterialByMonth(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 申领单--收料确认
    /// </summary>
    /// <param name="context"></param>
    protected void ReciveConfirmNPMaterialApplyBill(HttpContext context) 
    {
        var para = new Dictionary<string, string>();
        para.Add("IDS", context.Request["ids"].ToString());
        uMESProcessResult result = new uMESProcessResult();
        result.Result = m_amab.ReciveConfirmAuxMaterialApplyBill(para);
        result.Message = result.Result ? "确认成功" : "确认失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    
    #endregion

    #region 年、月定额消耗设定
    /// <summary>
    /// 年、月定额消耗设定--新增
    /// </summary>
    /// <param name="context"></param>
    protected void AddYearAndMonth(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        result.Result = m_amab.AddYearAndMonthConsumeQuota(Getpara(context));
        result.Message = result.Result ? "新增成功" : "新增失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 年、月定额消耗设定--更新
    /// </summary>
    /// <param name="context"></param>
    protected void UpdateYearAndMonth(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        uMESProcessResult result = new uMESProcessResult();
        result.Result = m_amab.UpdateYearAndMonthConsumeQuota(Getpara(context));
        result.Message = result.Result ? "更新成功" : "更新失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private Dictionary<string, string> Getpara(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var ZSNOTPRODUCTMATERIALID = dt.Rows[0]["ZSNOTPRODUCTMATERIALID"].ToString();
        var ZSNOTPRODUCTMATERIALDETAILID = dt.Rows[0]["ZSNOTPRODUCTMATERIALDETAILID"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("ZSNOTPRODUCTMATERIALID", String.IsNullOrWhiteSpace(ZSNOTPRODUCTMATERIALID) ? Guid.NewGuid().ToString() : ZSNOTPRODUCTMATERIALID);
        para.Add("ZSNOTPRODUCTMATERIALDETAILID", String.IsNullOrWhiteSpace(ZSNOTPRODUCTMATERIALDETAILID) ? Guid.NewGuid().ToString() : ZSNOTPRODUCTMATERIALDETAILID);
        para.Add("WorkcenterID", dt.Rows[0]["WorkcenterID"].ToString());
        para.Add("ShiftID", dt.Rows[0]["TeamID"].ToString());
        para.Add("MaterialCode", dt.Rows[0]["MaterialCode"].ToString());
        para.Add("MaterialDesc", dt.Rows[0]["MaterialDesc"].ToString());
        para.Add("Year", dt.Rows[0]["Year"].ToString());
        para.Add("YearQty", dt.Rows[0]["YearQty"].ToString());
        para.Add("Month", dt.Rows[0]["Month"].ToString());
        para.Add("MonthQty", dt.Rows[0]["MonthQty"].ToString());
        para.Add("Notes", dt.Rows[0]["Notes"].ToString());
        para.Add("Type", context.Request["Type"].ToString());
        para.Add("CREATEEMPLOYEEID", m_UserInfo.EmployeeID.ToString());
        return para;
    }

    protected void DeleteYearAndMonthConsumeQuota(HttpContext context) {
        var para = new Dictionary<string, string>();
        para.Add("MIDS", context.Request["mids"].ToString());
        para.Add("IDS", context.Request["ids"].ToString());
        para.Add("Type", context.Request["type"].ToString());
        uMESProcessResult result = new uMESProcessResult();
        result.Result = m_amab.DeleteYearAndMonthConsumeQuota(para);
        result.Message = result.Result ? "删除成功" : "删除失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    
    /// <summary>
    /// 材料消耗定额(按年)
    /// </summary>
    /// <param name="context"></param>
    protected void GetYearConsumeQuota(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var para = new Dictionary<string, string>();
        para.Add("Description", dt.Rows[0]["Description"].ToString());
        para.Add("AuxmaterialName", dt.Rows[0]["AuxmaterialName"].ToString());
        para.Add("TeamID", dt.Rows[0]["TeamID"].ToString());
        para.Add("yearmonth", dt.Rows[0]["yearmonth"].ToString());
        para.Add("WorkcenterID", dt.Rows[0]["WorkcenterID"].ToString());
        para.Add("PageSize", pageSize);
        para.Add("CurrentPageIndex", pageNumber);
        uMESProcessResult result = m_amab.GetYearConsumeQuota(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 材料消耗定稿(按月)
    /// </summary>
    /// <param name="context"></param>
    protected void GetMonthConsumeQuota(HttpContext context)
    {
        var para = new Dictionary<string, string>();
        para.Add("IDS", context.Request["ids"].ToString());
        uMESProcessResult result = new uMESProcessResult();
        result.DBTable = m_amab.GetMonthConsumeQuota(para);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    #endregion
}